//
//  PlistJsonVC.m
//  sqliteToEnity
//
//  Created by hament on 13-8-21.
//  Copyright (c) 2013年 hament. All rights reserved.
//

#import "PlistJsonVC.h"
#import "HCoreConfig.h"
#import "HSqlManager.h"

#import "TableEnity.h"
#import "AttributeEnity.h"
#import "AppDelegate.h"
@interface PlistJsonVC ()

@property (strong) IBOutlet NSBox *selectBox;
@property (strong) IBOutlet NSBox *configBox;
@property (strong) IBOutlet NSBox *exportBox;

@property (strong) IBOutlet NSTextField *exportTitleLab;
@property (strong) IBOutlet NSTextField *sqliteTitleLab;

@property (strong) IBOutlet NSTextField *sqlitePathRemindTf;
@property (strong) IBOutlet NSTextField *exportRemindTf;

@property (strong) IBOutlet NSArrayController *dataSources;
@property (strong) IBOutlet NSArrayController *attridataSources;




- (IBAction)analysic:(NSButton *)sender;
- (IBAction)exportEnity:(NSButton *)sender;
-(void)checkDBPath:(NSString *)path;
-(BOOL)checkExportPath:(NSString *)path;

@end

@implementation PlistJsonVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}



-(void)awakeFromNib {
    
    self.publicConfig=[HCoreConfig shareConfig];

    /*reminder*/
    [self.sqlitePathRemindTf setHidden:YES];
    [self.exportRemindTf setHidden:YES];


    /*nsbox config*/
    //设置标题颜色
    [[self.selectBox titleCell] setTextColor:[NSColor colorWithCalibratedRed:85.0/255.0  green:123.0/255.0  blue:254.0/255.0 alpha:1.0]];
    [[self.configBox titleCell] setTextColor:[NSColor colorWithCalibratedRed:85.0/255.0  green:123.0/255.0  blue:254.0/255.0 alpha:1.0]];
    [[self.exportBox titleCell] setTextColor:[NSColor colorWithCalibratedRed:85.0/255.0  green:123.0/255.0  blue:254.0/255.0 alpha:1.0]];


        [self configTheExportDesWith:NSLocalizedString(@"plistExportConfig des", nil)];
    
}

#pragma mark
#pragma mark ------业务逻辑--------

-(void)checkDBPath:(NSString *)path{
    
    BOOL isOk=[HCoreConfig isDBPathOkWithPath:path];
    if (isOk) {
        [self.sqlitePathRemindTf setHidden:YES];
        

        NSArray * arr=[HSqlManager getAllEnitysWithPah:self.sqlitePath.stringValue];
        [self.dataSources setContent:arr];
        
        
        [self.view.window makeFirstResponder:self.exportFolderFd];
        
    } else{
        
        [self.sqlitePathRemindTf setHidden:NO];
        
    }
    
}


-(BOOL)checkExportPath:(NSString *)path{
    BOOL isOk=[HCoreConfig exportFloderOkWithPath:path];
    
    if (isOk) {
        [self.exportRemindTf setHidden:YES];
    } else{
        [self.exportRemindTf setHidden:NO];
    }
    
    return isOk;
    
}

- (IBAction)analysic:(NSButton *)sender {
    NSString * path=[self.sqlitePath.stringValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    
    [self checkDBPath:path];
    
}


- (IBAction)exportEnity:(NSButton *)sender {
    NSString * path=[self.exportFolderFd.stringValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    //导出
    if ([self checkExportPath:path]) {
        
        NSArray * datas=[self.dataSources content];
        
        
         NSString * dbpath=[self.sqlitePath.stringValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        //导出plist 
        if (self.exportPlist) {
            
            AppDelegate * appdelegate=(AppDelegate*)[NSApplication sharedApplication].delegate;
            [appdelegate addGlobalRemind];
            
             dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [HCoreConfig exportToPlist:datas folderPath:path dbPath:dbpath];
                 
                 dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [appdelegate finishProcessing];
                     
                 });
                 
                 
             });
        }
        //json
        else {

            AppDelegate * appdelegate=(AppDelegate*)[NSApplication sharedApplication].delegate;
            [appdelegate addGlobalRemind];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                 [HCoreConfig exportToJson:datas folderPath:path dbPath:dbpath];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [appdelegate finishProcessing];
                    
                });
                
                
            });
        }
        
        
        
    }
    
    
    
    
}

- (IBAction)chooseDBpath:(NSButton *)sender {
    
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowsMultipleSelection:NO];
    [panel setCanChooseDirectories:YES];
    [panel setCanChooseFiles:YES];
    [panel setResolvesAliases:YES];
    
    NSString *panelTitle = NSLocalizedString(@"Choose a file", @"Title for the open panel");
    [panel setTitle:panelTitle];
    
    NSString *promptString = NSLocalizedString(@"Choose", @"Prompt for the open panel prompt");
    [panel setPrompt:promptString];
    
    PlistJsonVC *  weakSelf = self;
    
    [panel beginSheetModalForWindow:[weakSelf.view window] completionHandler:^(NSInteger result){
        
        // Hide the open panel.
        [panel orderOut:self];
        
        // If the return code wasn't OK, don't do anything.
        if (result != NSOKButton) {
            return;
        }
        // Get the first URL returned from the Open Panel and set it at the first path component of the control.
        NSURL *url = [[panel URLs] objectAtIndex:0];
        // [weakSelf.pathControl setURL:url];
        self.sqlitePath.stringValue=url.path;
        [weakSelf checkDBPath:url.path];
        
    }];
}


- (IBAction)chooseExportfolder:(NSButton *)sender {
    
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowsMultipleSelection:NO];
    [panel setCanChooseDirectories:YES];
    [panel setCanChooseFiles:NO];
    [panel setResolvesAliases:YES];
    
    //    NSString *panelTitle = NSLocalizedString(@"Choose a file", @"Title for the open panel");
    //    [panel setTitle:panelTitle];
    
    NSString *promptString = NSLocalizedString(@"Choose", @"Prompt for the open panel prompt");
    [panel setPrompt:promptString];
    
    PlistJsonVC *  weakSelf = self;
    
    [panel beginSheetModalForWindow:[weakSelf.view window] completionHandler:^(NSInteger result){
        
        // Hide the open panel.
        [panel orderOut:self];
        
        // If the return code wasn't OK, don't do anything.
        if (result != NSOKButton) {
            return;
        }
        // Get the first URL returned from the Open Panel and set it at the first path component of the control.
        NSURL *url = [[panel URLs] objectAtIndex:0];
        // [weakSelf.pathControl setURL:url];
        self.exportFolderFd.stringValue=url.path;
        [weakSelf checkExportPath:url.path];
    }];
    
    
}



-(void)configTheExportDesWith:(NSString*)content{
    
    
    //阴影
    NSShadow* newShadow = [[NSShadow alloc] init];
    newShadow.shadowColor = [NSColor orangeColor];
    newShadow.shadowBlurRadius = 4.0;
    
    //字体
    NSFont * font=[NSFont fontWithName:@"helvetica" size:13];
    
    //颜色
    NSColor * color=[NSColor blueColor];
    
    NSDictionary* attrs = @{NSShadowAttributeName:newShadow,
                            NSFontAttributeName:font,
                            NSForegroundColorAttributeName:color};
    
    
    
    NSMutableAttributedString* text = [[NSMutableAttributedString alloc] initWithString:content attributes:attrs];
	//[text addAttributes:attrs range:NSMakeRange(0, self.exportDesTv.string.length)];
    
    [self.exportDesTv.textStorage setAttributedString:text];
}


-(void)resetUI{

//设置导出说明
//一些翻译

    //导出plist
    if (self.exportPlist) {
        
        
        
    }
    //导出json
    else {
    
    
    
    }
    
    
    
}




#pragma mark
#pragma mark ------textfield delegate-------





@end
